<template>
	<view class="container">
		<!-- 可滑动的swiper -->
		<view class="swiper-container">
			<swiper :indicator-dots="true"
				current="currentSwiper"
				:autoplay="false"
				:circular="true"
				:interval="3000"
				:duration="500"
				@change="handleSwiperChange"
				style="width: 690rpx; margin: 0 auto;">
				<swiper-item v-for="(item, index) in spreadData"
					:key="index">
					<view class="slide-item">
						<view class="slide-image">
							<image class="pic"
								:src="item.pic" />
						</view>

						<!-- 新增组件：图片下方的文字和图片区域 -->
						<view class="info-container"
							v-if="codeSrc != ''">
							<!-- 左侧文字部分 -->
							<view class="text-section">
								<view class="top-text">{{ nickName }}</view>
								<view class="bottom-text">邀请您加入{{ siteName }}</view>
							</view>
							<!-- 右侧图片部分 -->
							<view class="image-section">
								<image :src="codeSrc"
									class="right-image"
									mode="aspectFit" />
							</view>
						</view>
					</view>
				</swiper-item>
			</swiper>
		</view>

		<view class="button_box">
			<button class="item"
				@tap="saveImage">
				<image src="../static/haibao.png"></image>
				<view>保存海报</view>
			</button>
			<button class="item"
				open-type="share">
				<image src="../static/alipay.png"></image>
				<view>分享好友</view>
			</button>
		</view>
		<!-- 按钮区域 -->
		<!-- <view class="button-group">
			<button class="btn save-btn"
				@tap="saveImage">保存图片</button>
			<button class="btn share-btn"
				@tap="shareFriend">分享好友</button>
		</view> -->

		<!-- 用于绘制并保存图片的canvas（必须隐藏） -->
		<canvas id="shareCanvas"
			style="width: 690px; height: 1100px; position: fixed; left: -9999rpx; top: -9999rpx;"></canvas>
	</view>
</template>

<script>
import { getUserInfo, spreadBanner, userShare, routineCode, spreadMsg, imgToBase } from '@/api/user.js';
import { mapGetters } from 'vuex';

export default {
	data() {
		return {
			currentSwiper: 0,
			spreadData: [],
			codeSrc: '',
			nickName: '',
			siteName: ''
		};
	},
	computed: {
		...mapGetters(['uid']),
	},
	onLoad() {
		this.getPicApi();
	},

	onShareAppMessage() {
		let uid = this.uid ? this.uid : 0;
		return {
			title: '邀请您加入途安车服',
			path: '/pages/index/index?spid=' + uid
		};
	},

	methods: {
		async getPicApi() {
			uni.showLoading({
				title: '加载中',
				mask: true
			});

			let res = await spreadMsg();

			if (res.data.spread.length == 0) {
				setTimeout(() => {
					uni.showToast({
						title: '暂无分享图片',
						icon: 'none'
					});
				}, 1500);
				uni.navigateBack({ delta: 1 });
				return;
			}

			this.spreadData = res.data.spread;
			this.nickName = res.data.nickname;
			this.siteName = res.data.site_name;
			this.getCodeApi();
		},

		async getCodeApi() {
			let res = await routineCode();
			uni.hideLoading();
			this.codeSrc = res.data.url;
		},

		handleSwiperChange(e) {
			this.currentSwiper = e.detail.current;
		},

		/**
		 * 保存图片功能实现
		 * 将当前显示的幻灯片内容绘制到canvas并保存为图片
		 */
		saveImage() {
			if (!this.spreadData || !this.spreadData[this.currentSwiper]) {
				uni.showToast({ title: '图片数据未加载完成', icon: 'none' });
				return;
			}

			// 支付宝小程序不需要提前检查权限，保存时会自动请求
			this.drawAndSaveImage();
		},

		/**
		 * 绘制图片并保存到相册
		 * 将当前显示的幻灯片内容绘制到canvas，然后保存
		 */
		async drawAndSaveImage() {
			let ctx;
			try {
				// 尝试使用支付宝小程序原生API
				if (typeof my !== 'undefined' && my.createCanvasContext) {
					// 支付宝小程序原生API不需要传入this
					ctx = my.createCanvasContext('shareCanvas');
				} else {
					// 使用uni API
					ctx = uni.createCanvasContext('shareCanvas');
				}

				// 验证ctx是否创建成功
				if (!ctx || typeof ctx.draw !== 'function') {
					console.error('创建Canvas上下文失败', ctx);
					uni.showToast({ title: '生成图片失败', icon: 'none' });
					return;
				}

				const currentImage = this.spreadData[this.currentSwiper];
				// 获取设备像素比
				const dpr = uni.getSystemInfoSync ? uni.getSystemInfoSync().pixelRatio || 1 : 1;

				// 设置canvas宽高
				const canvasWidth = 690;
				const canvasHeight = 1100;

				// 绘制白色背景
				ctx.setFillStyle('#ffffff');
				ctx.fillRect(0, 0, canvasWidth, canvasHeight);

				// 由于支付宝小程序中Image对象不可用，直接进行绘制
				const img = await this.downloadFilestoreImage(currentImage.pic);
				// 调整图片高度以适应新的画布高度
				ctx.drawImage(img, 0, -4, canvasWidth, 900);

				// 如果有二维码和文字信息，继续绘制
				if (this.codeSrc !== '') {
					// 设置文字样式 - 调整为新的页面效果
					ctx.setFontSize(36); // 增大字体以匹配更大的画布
					ctx.setFillStyle('#333333');
					ctx.font = 'bold 36px sans-serif';

					// 绘制顶部文字（昵称）- 调整y坐标以适应新的画布高度
					ctx.fillText(this.nickName, 40, 980);

					// 绘制底部文字（邀请信息）- 调整字体大小和y坐标
					ctx.setFontSize(28); // 增大字体以匹配更大的画布
					ctx.setFillStyle('#888888');
					ctx.font = '28px sans-serif';
					ctx.fillText(`邀请您加入${this.siteName}`, 40, 1034); // 调整y坐标以适应新的间距

					// 绘制右侧二维码图片 - 调整大小和位置以适应新的画布高度
					ctx.drawImage(this.codeSrc, canvasWidth - 200, 900, 170, 170);
				}

				console.log('开始执行ctx.draw');
				// 开始绘制 - 支付宝小程序中回调函数没有参数
				ctx.draw(false, () => {
					console.log('ctx.draw回调执行了');
					// 绘制完成后，将canvas导出为图片
					const exportOptions = {
						canvasId: 'shareCanvas',
						x: 0,
						y: 0,
						width: canvasWidth,
						height: canvasHeight,
						destWidth: canvasWidth,
						destHeight: canvasHeight,
						success: (res) => {
							// 保存图片到相册
							if (typeof my !== 'undefined' && my.saveImage) {
								// 优先使用支付宝小程序原生API
								my.saveImage({
									url: res.tempFilePath,
									showActionSheet: true,
									success: () => {
										uni.showToast({ title: '保存成功', icon: 'success' });
									},
									fail: (err) => {
										console.error('保存图片失败', err);
										// 支付宝小程序特有的错误处理
										if (err.error && err.error.includes('PERMISSION')) {
											uni.showModal({
												title: '提示',
												content: '保存图片需要您的授权，是否前往设置开启？',
												confirmText: '去设置',
												success: (modalRes) => {
													if (modalRes.confirm && my.openSetting) {
														my.openSetting();
													}
												}
											});
										} else {
											uni.showToast({ title: '保存失败', icon: 'none' });
										}
									}
								});
							} else if (uni.saveImageToPhotosAlbum) {
								// 使用uni API
								uni.saveImageToPhotosAlbum({
									filePath: res.tempFilePath,
									success: () => {
										uni.showToast({ title: '保存成功', icon: 'success' });
									},
									fail: (err) => {
										console.error('保存图片失败', err);
										uni.showToast({ title: '保存失败', icon: 'none' });
									}
								});
							}
						},
						fail: (err) => {
							console.error('canvas导出图片失败', err);
							uni.showToast({ title: '生成图片失败', icon: 'none' });
						}
					};

					// 根据环境选择合适的API导出图片
					if (typeof my !== 'undefined' && my.canvasToTempFilePath) {
						my.canvasToTempFilePath(exportOptions);
					} else {
						uni.canvasToTempFilePath(exportOptions);
					}
				});
				console.log('开始执行ctx.draw2');
			} catch (error) {
				console.error('绘制图片过程中发生错误', error);
				uni.showToast({ title: '生成图片失败', icon: 'none' });
			}
		},

		downloadFilestoreImage(url) {
			return new Promise((resolve, reject) => {
				let that = this;
				uni.downloadFile({
					url: url,
					success: function (res) {
						resolve(res.tempFilePath);
					},
					fail: function () {
						return that.$util.Tips({
							title: ''
						});
					}
				});
			})
		},

		shareFriend() {
			// 支付宝小程序分享好友逻辑
			if (typeof my !== 'undefined' && my.shareAppMessage) {
				my.shareAppMessage({
					title: '途安车服',
					content: `${this.nickName}邀请您加入途安车服`,
					// 可以添加分享图片等其他参数
				});
			} else {
				console.log('分享好友功能');
				uni.showToast({ title: '分享功能暂未实现', icon: 'none' });
			}
		}
	}
};
</script>

<style scoped
	lang="scss">
	.container {
		padding: 30rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		background-color: #f5f5f5;
		min-height: 100vh;
	}

	.swiper-container {
		margin-bottom: 60rpx;
	}

	.slide-item {
		width: 100%;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		background-color: white;
	}

	.slide-image {
		width: 100%;
		height: 900rpx;
		object-fit: cover;

		.pic {
			width: 100%;
			height: 900rpx;
		}
	}

	/* 新增样式：图片下方的信息容器 */
	.info-container {
		width: 690rpx;
		background-color: white;
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 0rpx 30rpx 20rpx;
		box-sizing: border-box;
	}

	.text-section {
		flex: 1;
		margin-right: 20rpx;
	}

	.top-text {
		font-size: 36rpx;
		color: #333333;
		margin-bottom: 20rpx;
		font-weight: bold;
	}

	.bottom-text {
		font-size: 28rpx;
		color: #666666;
	}

	.image-section {
		width: 170rpx;
		height: 170rpx;
	}

	.right-image {
		width: 100%;
		height: 100%;
	}


	/* swiper指示器样式 */
	.swiper-indicator {
		display: flex;
		justify-content: center;
		margin-top: 20rpx;
	}

	.swiper-indicator-item {
		width: 12rpx;
		height: 12rpx;
		border-radius: 50%;
		background-color: #d9d9d9;
		margin: 0 8rpx;
	}

	.swiper-indicator-item-active {
		background-color: #1aad19;
		width: 30rpx;
		border-radius: 6rpx;
	}

	.button_box {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		height: 170rpx;
		display: flex;
		background-color: white;
		border-top: 1rpx solid #eee;
		box-sizing: border-box;
		padding: 0 30rpx;
	}

	.button_box .item {
		flex: 1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: transparent;
		border: none;
		box-shadow: none;
		padding: 0;
		height: 100%;
	}

	.button_box .item image {
		width: 80rpx;
		height: 80rpx;
		margin-bottom: 16rpx;
	}

	.button_box .item view {
		font-size: 28rpx;
		color: #333;
	}
</style>
